package al.xc.liveapi.aop;

import al.xc.common.exception.ResultCodeDefine;
import al.xc.common.exception.SelfBaseException;
import al.xc.liveapi.data.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常处理
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public ResultVo<Object> handleException(Exception e) {
        log.debug("handleException", e);
        Integer resultCode = ResultCodeDefine.EXCEPTION.getCode();
        String errorInfo = "";
        if (e instanceof NullPointerException) {
            errorInfo = "空指针异常";
        } else if (e instanceof HttpMessageNotReadableException) {
            errorInfo = "请求参数匹配异常错误," + e.getLocalizedMessage();
        } else if (e instanceof SelfBaseException) {
            SelfBaseException re = (SelfBaseException) e;
            errorInfo = re.getMessage();
            resultCode = re.getCode();
        } else {
            errorInfo = e.getMessage();
        }

        ResultVo<Object> resultVo = new ResultVo<>();
        resultVo.setCode(resultCode);
        resultVo.setMsg(errorInfo);
        return resultVo;
    }
}
